package com.krui.iweibo.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.krui.iweibo.model.Task;
import com.krui.iweibo.model.UserInfo;
import com.krui.iweibo.ui.IweiboActivity;
import com.krui.iweibo.ui.WebViewActivity;
import com.krui.iweibo.utils.ImageFactory;
import com.krui.iweibo.utils.OAuthUtils;
import com.krui.iweibo.utils.SharedPreferenceUtil;

public class MainService extends Service implements Runnable {

	/** 任务队列 */
	private static Queue<Task> tasks = new LinkedList<Task>();

	private static List<Activity> appActivities = new ArrayList<Activity>();
	/** 线程是否在运行 */
	private boolean isRun = false;

	private AccessToken accessToken = null;
	private String authorizationURL = null;
	
	private static Weibo weibo = null;
	
	//当前系统登录用户
	private static UserInfo currentUser;
	

	static
	{
		
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		weibo = new Weibo();
		
	}
	
	
	
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			
			case Task.WEIBO_LOGIN:
				//更新UI
				
				IweiboActivity loginActivity = (IweiboActivity) getActivityByName("LoginActivity");
				loginActivity.refresh(msg.obj);
				break;
				
			case Task.GET_ACCESS_TOKEN:
				IweiboActivity authActivity = (IweiboActivity) getActivityByName("AuthActivity");
				authActivity.refresh(msg.obj);
				
				break;
				
			case Task.GET_AUTHORIZATIONURL:
				IweiboActivity authActivity_url = (IweiboActivity) getActivityByName("AuthActivity");
				authActivity_url.refresh(msg.obj);
				
				break;
				
			case Task.GET_USER_ICON:
				IweiboActivity authActivity_userIcon = (IweiboActivity) getActivityByName("AuthActivity");
				authActivity_userIcon.refresh(msg.obj);
				
				break;
				
			case Task.WEIBO_FRIEDNS_TIMELINE:
				IweiboActivity homeActivity = (IweiboActivity) getActivityByName("HomeActivity");
				homeActivity.refresh(msg.obj);
				break;

			default:
				break;
			}
		};
	};

	
	/**
	 * 添加一个activity到activity队列中
	 * @param act
	 */
	public static void addActivity(Activity act)
	{
		appActivities.add(act);
	}
	
	
	/**
	 * 添加任务到任务队列中
	 * 
	 * @param t
	 */
	public static void newTask(Task t) {
		tasks.add(t);
	}
	
	
	/**
	 * 根据activity name 得到activity实例对象
	 * @param name
	 * @return
	 */
	private Activity getActivityByName(String name){
		if (!appActivities.isEmpty()) {
			for(Activity activity : appActivities){
				if (activity != null) {
					if (activity.getClass().getName().indexOf(name) >= 0) {
						return activity;
					}
				}
			}
		}
		return null;
	}

	@Override
	public void onCreate() {

		Thread thread = new Thread(this);
		thread.start();
		isRun = true;
	}

	@Override
	public void run() {

		while (isRun) {
			Task task = null;
			if (!tasks.isEmpty()) {
				task = tasks.poll();// 当执行完一个任务后，将该任务从任务队列中移除
				if (task != null) {
					doTask(task);
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	/** 处理任务 */
	private void doTask(Task t) {
		Message msg = handler.obtainMessage();
		msg.what = t.getTaskId();

		switch (t.getTaskId()) {
		
		//登录
		case Task.WEIBO_LOGIN:
			System.out.println("dotask >>>>>> user login ");
			
			currentUser = (UserInfo)t.getTaskParams().get("loginUser");
			//必须设置，授权用户才有权限访问API
			weibo.setToken(currentUser.getToken(),currentUser.getTokenSecret());
			
			msg.obj = currentUser;
			
			break;
			
			
		//获取token
		case Task.GET_ACCESS_TOKEN:
			try {
				while (accessToken == null) {
					accessToken = OAuthUtils.getRequestToken().getAccessToken(WebViewActivity.PIN);
				}
				
				msg.obj = accessToken;
				
			} catch (WeiboException e) {
				e.printStackTrace();
			}
			
			break;
			
			
		//获取授权URL
		case Task.GET_AUTHORIZATIONURL:
			try {
				while(authorizationURL == null){
					authorizationURL = OAuthUtils.getAuthorizationURL();
				}
				msg.obj = authorizationURL;
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
			
			
			
		//获取头像信息
		case Task.GET_USER_ICON:
			UserInfo userInfo = (UserInfo)t.getTaskParams().get("user");
			//必须设置，授权用户才有权限访问API
			weibo.setToken(userInfo.getToken(),userInfo.getTokenSecret());
			
			try {
				User weiboUser = weibo.showUser(userInfo.getUserId());
				
				Bitmap userIcon = ImageFactory.downLoadImage(weiboUser.getProfileImageURL());
				
				userInfo.setUserName(weiboUser.getName());
				userInfo.setUserIcon(userIcon);
				
				msg.obj = userInfo;
				
			} catch (WeiboException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			break;
			
			
		case Task.WEIBO_FRIEDNS_TIMELINE:
			try {
				//currentUser = (UserInfo) t.getTaskParams().get("loginUser");
				//weibo.setToken(currentUser.getToken(),currentUser.getTokenSecret());
				Paging page = new Paging(1, 20);
				List<Status> status = weibo.getFriendsTimeline(page);
				msg.obj = status;
			} catch (WeiboException e) {
				e.printStackTrace();
			}
			break;

		default:
			break;
		}
		
		handler.sendMessage(msg);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
